<?php
/******************************************************************************
 *
 *    OpenZoowa - Web App to manage events
 *    Copyright (C) 2008 Jesus Ruiz-Ayucar
 *
 *    This program is free software: you can redistribute it and/or modify
 *    it under the terms of the GNU Affero General Public License as
 *    published by the Free Software Foundation, either version 3 of the
 *    License, or (at your option) any later version.
 *
 *    This program is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *    GNU Affero General Public License for more details.
 *
 *    You should have received a copy of the GNU Affero General Public License
 *    along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 *****************************************************************************/
   class UserController {
      public function login() {
         global $lang;
         $template = Util::startupTemplate('user','login');
         $template->assign('title', $lang['login']);
         $template->display('index.tpl');
      }

      public function show() {
         global $lang;
         if(isset($_GET['id'])) {
            $user = new User($_GET['id']);
            if ($user->getId() == $_GET['id']) {
               $template = Util::startupTemplate('user','show');
               $template->assign('title', $lang['profile']);
               $template->assign('user_obj', $user);
               $template->display('index.tpl');
            } else {
               echo "404";
            }
         } else {
            echo "404";
         }
      }

      public function activate() {
      }

      public function recover() {
         global $lang, $current_user;
         session_start();
         if($_SERVER['REQUEST_METHOD'] == 'POST' &&
            !empty($_POST['email']) &&
            $_SESSION['captcha'] == $_POST['captcha'] &&
            $current_user->sendRecover($_POST['email']))
         {
            // Han rellenado el formulario y le hemos enviado la contraseña
            unset($_SESSION['captcha']);
         } elseif(!empty($_GET['k'])) {
            // Nos llega una key. Quieren recuperar la cuenta
            if ($current_user->recover($_GET['login'], $_GET['n'], $_GET['k'])) {
               header('Location: /index.php?c=user&a=edit&id='.$current_user->getId());
            } else {
               header('Location: /index.php?c=user&a=recover');
            }
         } else {
            // Página en la que mostramos el formulario
            $template = Util::startupTemplate('user','recover');
            $template->assign('title', $lang['recover_title']);
            $template->display('index.tpl');
         }
      }

      public function register() {
         global $lang;
         if ($_SERVER['REQUEST_METHOD'] == 'GET') {
            $template = Util::startupTemplate('user','register');
            $template->assign('title', $lang['register_title']);
            $template->display('index.tpl');
         } else {
            global $current_user;
            session_start();
            $error = null;

            if ($_SESSION['captcha'] != $_POST['captcha']) {
               Util::addErrorMsg($error, $lang['login_err_captcha']);
            } else {
               unset($_SESSION['captcha']);
            }

            if ($_POST['legal'] != 'ok') {
               Util::addErrorMsg($error, $lang['use_terms_err']);
            }

            Util::addErrorMsg($error,$current_user->setLogin($_POST['login']));
            Util::addErrorMsg($error,$current_user->setEmail($_POST['email']));
            Util::addErrorMsg($error,$current_user->setPassword($_POST['password'], $_POST['password2']));

            if (empty($error)) {
               // Procedemos al registro
               $current_user->add();
               if ($GLOBALS['check_mail']) {
                  header('Location: /index.php?c=user&a=endregister');
               } else {
                  $current_user->activate();
                  $current_user->SetIDCookie(1,false);
                  header('Location: /index.php?c=user&a=show&id='.$current_user->getId());
               }
            } else {
               $template = Util::startupTemplate('user','register');
               $template->assign('title', $lang['register_title']);
               $template->assign('errors', $error);
               $template->display('index.tpl');
            }
         }
      }

      public function endregister() {
         $template = Util::startupTemplate('user','endregister');
         $template->assign('title', $lang['register_title']);
         $template->display('index.tpl');
      }

      public function auth() {
         global $current_user, $lang;
         session_start();

         $template = Util::startupTemplate('user','login');
         $template->assign('title', $lang['register_title']);

         $errors = null;
         // Comprobamos captcha si no es el primer intento
         if($_SESSION['captcha'] != $_POST['captcha']) {
            unset($_SESSION['captcha']);
            $errors[] = $lang['login_err_captcha'];
         } elseif (!$current_user->authenticate(
            $_POST['login'], $_POST['password'], $_POST['persistent']))
         {
            // Si el captcha es correcto comprobamos login y password
            $errors[] = $lang['login_err_pass'];
         } else {
            // Si eso no ha fallado, entonces son correctos
            unset($_SESSION['captcha']);
            header('Location: /index.php?c=user&a=show&id='.$current_user->getId());
            die;
         }
         $template->assign('errors',$errors);
         $template->assign('captcha', true);
         $template->display('index.tpl');
      }

      public function logout() {
         global $current_user;
         $current_user->logout('/index.php?usuario='.$current_user->getLogin());
      }

      public function edit() {
         global $current_user;
         if($current_user->getId()) {
            $template = Util::startupTemplate('user','edit');
            $template->assign('title', $lang['user_edit']);
            $template->assign('user_obj', $current_user);
            $template->display('index.tpl');
         }
      }

      public function update() {
         global $current_user;
         if(!empty($_POST['password'])) {
            Util::addErrorMsg($error,
               $current_user->setPassword(
                  $_POST['password'],
                  $_POST['password2']
               )
            );
         }
         Util::addErrorMsg($error,$current_user->setEmail($_POST['email']));
         if(!empty($_FILES['avatar']['tmp_name'])) {
            Util::addErrorMsg(
               $error,$current_user->setAvatar($_FILES['avatar'])
            );
         } elseif ($_POST['del_avatar'] == 1){
            Util::addErrorMsg($error,$current_user->setAvatar(null));
         }

         if($errors) {
            $template = Util::startupTemplate('user','edit');
            $template->assign('title', $lang['user_edit']);
            $template->assign('errors', $errors);
         } elseif ($current_user->update()) {
            $url ='Location: index.php?c=user&a=show&id='.$current_user->getId();
            header($url);
         } else {
            die("Error inesperado al actualizar usuario");
         }
      }
   }
?>